<template>
	<div>
    <!-- 新增/编辑人员 -->
		<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="close" :close-on-click-modal="false" width="800px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input 
                v-model="temp.name" 
                placeholder="请输入姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="temp.phone"
                placeholder="请输入手机号"
                :disabled="dialogStatus === 'update' ? true: false"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-cascader
                style="width: 100%;"
                value="id" 
                placeholder="选择部门"
                :show-all-levels="false"
                v-model="temp.department"
                :options="departmentData"
                :props="selectProps"
                @change="handleChange"
                clearable></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" v-if="temp.type && temp.type > 0">
            <el-form-item label="权限范围" prop="permissions">
              <div class="permission">
                <el-checkbox-group v-model="temp.permissions">
                  <el-checkbox v-for="item in pList" :label="item.id" v-model="item.checked" :key="item.id">{{ item.name }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
            <!-- <el-form-item label="权限范围" prop="permissions">
              <div class="permission">
                <div class="title">施工票管理:</div>
                <el-checkbox-group v-model="temp.permissions">
                  <el-checkbox :label="4" >施工票一览</el-checkbox>
                  <el-checkbox :label="5" >施工票审批</el-checkbox>
                </el-checkbox-group>
              </div>
              <div class="permission">
                <div class="title">视频督察:</div>
                <el-checkbox-group v-model="temp.permissions">
                  <el-checkbox :label="6" >回放视频督察</el-checkbox>
                  <el-checkbox :label="7" >实时视频督察</el-checkbox>
                </el-checkbox-group>
              </div>
              <div class="permission">
                <div class="title">人员权限管理:</div>
                <el-checkbox-group v-model="temp.permissions">
                  <el-checkbox :label="8" >人员管理</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item> -->
          </el-col>
          <el-col :span="24" v-else>
            <el-form-item label="权限范围" prop="permissions">
              <span>管理员帐号无需修改权限！！！</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">
          取消
        </el-button>
        <el-button type="primary" @click="saveUser()">
          确认
        </el-button>
      </div>
    </el-dialog>
	</div>
</template>

<script>
  import { userSave } from '@/api/usrs/index'
	export default {
		name: 'userDialog',
    props: {
      showDialog: {
        type: Boolean
      },
      dialogStatus: {
        type: String
      },
      userinfo: {
        type: Object
      },
      permissionList: {
        type: Array
      },
      departmentList: {
        type: Array
      }
    },
		data() {
			return {
        elLoading: false,
        temp: {
          name: '',
          phone: null,
          department: [],
          permissions: []
        },
        pList: [],
        textMap: {
					create: '添加人员',
					update: '编辑人员'
				},
				dialogFormVisible: false,
				departmentData: [],
        selectProps: {
					value: 'id',
					checkStrictly: true
				},
        rules: {
          name: [
						{ required: true, message: '用户姓名不能为空', trigger: 'blur'},
						{ min:1, max: 10, message: '限制长度10字以内', trigger: 'blur' }
					],
          phone: [
            { required: true, message: '手机号不能为空', trigger: 'blur'},
            {
              pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
              message: "请输入正确格式手机号",
              trigger: "blur",
            },
          ],
          department: [{ required: true, message: '请选择部门', trigger: 'change' }],
          permissions: [
            { type: 'array', required: true, message: '请选择权限范围', trigger: 'change' }
          ],
        },
        loading: null
			};
		},
		mounted() {
			this.dialogFormVisible = this.showDialog
      this.departmentData = this.departmentList

      this.pList = []
      this.permissionList.forEach(item=>{
        let obj = {...item}
        obj.checked = false
        this.pList.push(obj)
      })

      if(this.dialogStatus === 'update') {
        //寻找父级
        let result = []
        this.getParentIds(this.departmentData, this.userinfo.departmentId, result)
        let ids = result.map(d=> d.id)
        // this.temp.permissions = this.temp.permissionIds
        this.temp = {
          id: this.userinfo.id,
          status: this.userinfo.status,
          type: this.userinfo.type,
          name: this.userinfo.name,
          phone: this.userinfo.phone,
          department: ids,
          permissions: this.userinfo.permissionIds
        }
      } else {
        this.temp = {
          name: '',
          status: 1,
          type: 1,
          phone: null,
          department: [],
          permissions: []
        }
      }
		},
		methods: {
      //获取上级部门ids
			getParentIds(data, id, result) {
				for (let i in data) {
					let item = data[i]
					if (item.id === id) {
						//将查找到的目标数据加入结果数组中
						//可根据需求unshift(item.id)或unshift(item)
						result.unshift(item)
						return true
					}
					if (item.children && item.children.length > 0) {
						let ok = this.getParentIds(item.children, id, result)
						if (ok) {
							result.unshift(item)
							return true
						}
					}
				}
				//走到这说明没找到目标
				return false
			},
      handleChange() {
				// console.log(this.departmentTemp)
			},
			close() {
        this.dialogFormVisible = false
        this.$emit('close')
      },
      saveUser() {
        this.$refs['dataForm'].validate((valid) => {
					if (valid) {
            let result = []
            this.getParentIds(this.departmentData, this.temp.department[this.temp.department.length - 1], result)
            let dep = result[result.length - 1]
            // let pList = []
            // this.pList.forEach(item=> {
            //   item.chindren.forEach(item1 => {
            //     if(this.temp.permissions.indexOf(item1.id) != -1) {
            //       pList.push(item.id)
            //       pList.push(item1.id)
            //     }
            //   })
            // })

            var newArr = [...this.temp.permissions];
            newArr.sort((a,b) => a-b)
            let user = {
              name: this.temp.name,
              phone: this.temp.phone,
              type: this.temp.type,
              departmentId: dep.id,
              departmentName: dep.name,
              status: this.temp.status,
              statusText: this.temp.status === 1 ? '启用' : '禁用',
              permissionIds: newArr
            }
            if(this.temp.id) user.id = this.temp.id
            this.openLoading()
            userSave(user).then(res=> {
              this.closeLoading()
              this.$emit('refreshUser')
              this.dialogFormVisible = false
              this.$emit('close')
            }).catch(err=>{
              this.closeLoading()
              console.log(err)
            })
					}
				})
      },
      openLoading(){
        this.elLoading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      },
      closeLoading(){
        this.elLoading.close();
      },
		},
	}
</script>

<style lang="scss" scoped>
.permission {
  display: flex;
  .title {
    width: 100px;
    margin-right: 20px;
    text-align: right;
  }
}
::v-deep .el-checkbox {
  width: 110px;
}
</style>
